#include "CodeExercise.h"
#define PREFIX "./Tests/"
using namespace std;
Exercise::Exercise(std::string input_filename, std::string output_filename, int total_columns) {
    this->input_filename = PREFIX + input_filename;
    this->output_filename = PREFIX + output_filename;
    this->column_num = total_columns;
    this->input_stream = std::ifstream(this->input_filename);
    this->output_stream = std::ofstream(this->output_filename);
}

Exercise::~Exercise() {
    this->input_stream.close();
    this->output_stream.close();
}

int Exercise::next_line(std::string & str) {
    if (!getline(this->input_stream, str))
        return -1;
    return 0;
}

vector<string> Exercise::separate_string(const std::string &s, char separator) {
    vector<string> result;
    unsigned int posBegin = 0;
    unsigned int posEnd = 0;
    while(posEnd != s.length()){
        if (s[posEnd] == separator){
            result.push_back(s.substr(posBegin, posEnd - posBegin));
            posBegin = posEnd + 1;
        }
        posEnd++;
    }
    if (posEnd != posBegin)
        result.push_back(s.substr(posBegin, posEnd));
    return result;
}
void Exercise::run() {
    string str;
    while (this->next_line(str) != -1) {
        vector<string> vec = this->separate_string(str, this->separator);
        int64_t time_stamp = stoll(vec[0]);
        string symbol = vec[1];
        int64_t quality = stoll(vec[2]);
        int64_t price = stoll(vec[3]);
        // find the symbol in map
        if (this->statistic_map.find(symbol) != this->statistic_map.end()) {
            Statistic& statistic = this->statistic_map[symbol];
            statistic.feed_data(time_stamp, quality, price);
        }
        else{
            Statistic statistic(symbol);
            statistic.feed_data(time_stamp, quality, price);
            this->statistic_map[symbol] = statistic;
        }
    }
    for (auto & s : this->statistic_map)
        s.second.finish();
}
void Exercise::write_to_file() {
    for (auto & s : this->statistic_map){
        Statistic & statistic = s.second;
        output_stream<<statistic.symbol<<','<<statistic.max_time_stamp<<','<<statistic.volume<<','
            <<statistic.weighted_average_price<<','<<statistic.max_price<<endl;
    }
}
